privatevoidgrow(int minCapacity){ // overflow-conscious code int oldCapacity = elementData.length; // 1.5倍增长 int newCapacity = oldCapacity + (oldCapacity >> 1); if (newCapacity - minCapacity < 0) newCapacity = minCapacity; if (newCapacity - MAX_ARRAY_SIZE > 0) newCapacity = hugeCapacity(minCapacity); // minCapacity is usually close to size, so this is a win: elementData = Arrays.copyOf(elementData, newCapacity); }
3. Add(int index, E e) 方法
这个方法比较简单和上面基本一样,然后只是最后放元素的时候的操作不一样,他是采用了 System.arraycopy 从自己向自己拷贝,目的就在于覆盖元素。 注意一个规律这里面只要涉及下标的操作的很多不是自己手写 for 循环而是采用类似的拷贝覆盖的方法。算是一个小技巧。
public E remove(int index){ rangeCheck(index); modCount++; E oldValue = elementData(index); int numMoved = size - index - 1; //覆盖 if (numMoved > 0) System.arraycopy(elementData, index+1, elementData, index, numMoved); elementData[--size] = null; // clear to let GC do its work return oldValue; }
privatevoidwriteObject(java.io.ObjectOutputStream s) throws java.io.IOException{ // Write out element count, and any hidden stuff int expectedModCount = modCount; s.defaultWriteObject(); // Write out size as capacity for behavioural compatibility with clone() s.writeInt(size); // Write out all elements in the proper order. for (int i=0; i<size; i++) { s.writeObject(elementData[i]); } if (modCount != expectedModCount) { thrownew ConcurrentModificationException(); } }
privateclassItrimplementsIterator<E> { int cursor; // index of next element to return int lastRet = -1; // index of last element returned; -1 if no such int expectedModCount = modCount; finalvoidcheckForComodification(){ if (modCount != expectedModCount) thrownew ConcurrentModificationException(); } }
3. forEach
这个是一个函数式编程的方法,看看他的参数 forEach(Consumer<? super E> action) 很有意思里面接受是一个函数式的接口,我们里面回调了 Consumer 的 accept 所以我们只需要传入一个函数接口就能对每一个元素处理。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
@Override publicvoidforEach(Consumer<? super E> action){ Objects.requireNonNull(action); finalint expectedModCount = modCount; @SuppressWarnings("unchecked") final E[] elementData = (E[]) this.elementData; finalint size = this.size; for (int i=0; modCount == expectedModCount && i < size; i++) { //回调 action.accept(elementData[i]); } if (modCount != expectedModCount) { thrownew ConcurrentModificationException(); } }